package com.yimi.yinhepda.views.lan_huo_scan;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.pda.ym.entity.response.NoDataResponse;
import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.RecycleAdapter.LanHuoScanAdapter;
import com.pda.ym.base.CommonViewHolder;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.LanHuoChildTableDao;
import com.yimi.yinhepda.db.dao.LanHuoTableDao;
import com.yimi.yinhepda.db.table.LanHuoChildTable;
import com.yimi.yinhepda.db.table.LanHuoTable;
import com.yimi.yinhepda.entity.request.LanHuoStatusUpdateRequest;
import com.yimi.yinhepda.entity.response.QueryLanHuoDataResponse;
import com.yimi.yinhepda.entity.response.QueryLoginInfoResponse;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.yimi.yinhepda.utils.ListUtils;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author: lj
 * Date: 2019/5/20 14:13
 * Description: 揽货扫描
 */
public class LanHuoScanActivity extends BaseActivity implements CommonViewHolder.onItemCommonClickListener {

    /**
     * 揽货部门
     */
    private TextView tvDeptName;
    /**
     * 返回按钮
     */
    private Button ivBakck;
    /**
     * 揽货列表
     */
    private RecyclerView rvLanHuoListView;
    /**
     * 揽货集合
     */
    private List<LanHuoTable> mDataList;
    /**
     * 揽货实体
     */
    private LanHuoTable mLanHuoScanEntity;
    /**
     * 揽货扫描适配器
     */
    private LanHuoScanAdapter mAdapter;
    /**
     * 刷新按钮
     */
    private Button btnRefresh;
    /**
     * 提交按钮
     */
    private Button btnSubmit;
    /**
     * 撤销
     */
    private Button btnCancle;
    /**
     * 票数
     */
    private TextView tvPiaoNum;
    /**
     * 实操票数
     */
    private TextView tvRealPiaoNum;
    /**
     * 当前页数
     */
    private int currentPage;
    /**
     * 总页数
     */
    private int totalPage;
    /**
     * 一页数量
     */
    private final int pageSize = 100;
    private LanHuoTableDao mLanHuoTableDao;
    private LanHuoChildTableDao mLanHuoChildTableDao;

    public LanHuoScanActivity() {
        super(true);
    }

    @Override
    public String getPageName() {
        return "揽货扫描";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lan_huo_scan);

        ivBakck = findViewById(R.id.btn_back);
        ivBakck.setOnClickListener(this);
        rvLanHuoListView = findViewById(R.id.rv_lanHuo_list);
        tvDeptName = findViewById(R.id.tv_deptName);
        btnRefresh = findViewById(R.id.btn_refresh);
        btnRefresh.setOnClickListener(this);
        btnSubmit = findViewById(R.id.btn_submit);
        btnSubmit.setOnClickListener(this);
        btnCancle = findViewById(R.id.btn_cancle);
        btnCancle.setOnClickListener(this);
        tvPiaoNum = findViewById(R.id.tv_piaoNum);
        tvRealPiaoNum = findViewById(R.id.tv_realPiaoNum);

        tvDeptName.setText(SharedPreferUtil.getInstance().getValue(Common.DEPT_NAME));

        currentPage = 1;
        requestData();

        mLanHuoTableDao = new LanHuoTableDao();
        mLanHuoChildTableDao = new LanHuoChildTableDao();
        mDataList = new ArrayList<>();
        mAdapter = new LanHuoScanAdapter(this, mDataList, this);
        rvLanHuoListView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rvLanHuoListView.setAdapter(mAdapter);

        //查询登录用户信息
        queryLoginInfo();
    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            showToast("扫描运单失败！");
        } else {
            if (mLanHuoScanEntity != null) {
                mLanHuoScanEntity.setSelect(false);
            }

            if (!StringUtils.isWaybillNo(result)) {
                SoundVibratorManager.playSound(2);
                showToast("运单号不规范!");
                return;
            }

            boolean isExit = false;
            for (LanHuoTable item : mDataList) {
                if (item.getWaybillNo() != null) {
                    if (item.getChildList() != null) {
                        for (LanHuoChildTable childItem : item.getChildList()) {
                            if (childItem.getChildWaybillNo().equals(result)) {
                                if (childItem.isScan()) {
                                    showToast("运单已扫描");
                                    SoundVibratorManager.playSound(2);
                                    return;
                                }
                            }
                        }
                        if (item.getWaybillNo().toString().equals(result.substring(0, 12))) {
                            isExit = true;
                            LanHuoChildTable childItem = new LanHuoChildTable();
                            childItem.setScan(true);
                            childItem.setChildWaybillNo(result);
                            childItem.setOrderNo(item.getOrderNo());
                            childItem.setScanTime(DateHelper.getDateTimeFormateForSimple(new Date()));
                            childItem.setWaybillNo(item.getWaybillNo());
                            //已扫描的保存至本地
                            try {
                                item.setScanTime(DateHelper.getDateTimeFormateForSimple(new Date()));
                                item.setScan(true);
                                item.getChildList().add(childItem);
                                mLanHuoTableDao.insert(item);
                                mLanHuoChildTableDao.insert(childItem);
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                            mDataList = sortList(mDataList);
                            mAdapter.notifyDataSetChanged();
                            SoundVibratorManager.playSound(1);
                            statisticsPiaoNum();
                            break;
                        }
                    }
                }
            }
            if (!isExit) {
                showToast("该运单不在揽货列表中！");
                SoundVibratorManager.playSound(2);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_refresh:
                mDataList.clear();
                currentPage = 1;
                requestData();
                break;
            case R.id.btn_submit:
                if (mDataList == null || mDataList.isEmpty()) {
                    showToast("无可提交的数据！");
                    return;
                }
                boolean isScan = false;
                for (LanHuoTable item : mDataList) {
                    if (item.isScan()) {
                        isScan = true;
                    }
                }
                if (!isScan) {
                    showToast("请先扫描运单后再提交！");
                    return;
                }
                requestSubmit();
                break;
            case R.id.btn_cancle:
                if (mLanHuoScanEntity == null || !mLanHuoScanEntity.isSelect() || !mLanHuoScanEntity.isScan()) {
                    showToast("请选择一项已扫描的运单！");
                    SoundVibratorManager.playSound(2);
                    return;
                }
                int i = mLanHuoTableDao.deleteByWaybillNo(mLanHuoScanEntity.getOrderNo(), mLanHuoScanEntity.getWaybillNo());
                if (i != -1) {
                    //删除子单数据
                    int i2 = mLanHuoChildTableDao.deleteByWaybillNo(mLanHuoScanEntity.getOrderNo(), mLanHuoScanEntity.getWaybillNo());
                    if (i2 != -1) {
                        mLanHuoScanEntity.setScan(false);
                        mLanHuoScanEntity.setScanNum(0);
                        mLanHuoScanEntity.setSelect(false);
                        mLanHuoScanEntity.getChildList().clear();
                        mAdapter.notifyDataSetChanged();
                        showToast("已撤销！");
                        SoundVibratorManager.playSound(1);
                        statisticsPiaoNum();
                    } else {
                        showToast("无法删除子单数据！");
                    }
                } else {
                    showToast("无法删除运单数据！");
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClickListener(int position) {
        mLanHuoScanEntity = mDataList.get(position);
        if (mLanHuoScanEntity.isSelect()) {
            mLanHuoScanEntity.setSelect(false);
        } else {
            for (LanHuoTable entity : mDataList) {
                entity.setSelect(false);
            }
            mLanHuoScanEntity.setSelect(true);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemLongClickListener(int position) {

    }

    /**
     * 请求查询揽货数据
     */
    private void requestData() {
        showPgDlg("查询中...");
        Map<String, String> params = new HashMap<>();
        //打印成功
        params.put("printStatus", "2");
        //已受理
        params.put("orderStatus", "5");
        params.put("currentPage", String.format("%s", currentPage));
        params.put("pageSize", String.format("%s", pageSize));
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryLanHuoDataResponse.class)
                .setUrl(Constants.URL_LANHUO_DATA)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        QueryLanHuoDataResponse response = (QueryLanHuoDataResponse) obj;
                        if (response.getData() != null) {
                            List<LanHuoTable> records = response.getData().getRecords();
                            if (records != null) {
                                Iterator<LanHuoTable> it = records.iterator();
                                while (it.hasNext()) {
                                    LanHuoTable item = it.next();
                                    //打印成功和揽货成功的删除
                                    if (item.getOrderStatus() == 2 || item.getWaybillNo() == null || item.getQuantity() == null
                                            || item.getOrderNo() == null) {
                                        //删除揽货成功的运单
                                        it.remove();
                                        continue;
                                    }
                                    //查询本地是否有该运单，改变揽货状态
                                    List<LanHuoTable> list = mLanHuoTableDao.queryByWaybillNo(item.getOrderNo(), item.getWaybillNo());
                                    if (list != null && !list.isEmpty()) {
                                        for (LanHuoTable table : list) {
                                            //查询子单表
                                            List<LanHuoChildTable> childList = mLanHuoChildTableDao.queryByWaybillNo(table.getOrderNo(), table.getWaybillNo());
                                            if (childList != null && !childList.isEmpty()) {
                                                item.setScan(true);
                                                item.setScanNum(childList.size());
                                                item.setChildList(childList);
                                            }
                                        }
                                    }
                                }
                                mDataList.addAll(records);
                                //总页数
                                totalPage = response.getData().getTotalPage();
                                if (currentPage < totalPage) {
                                    //请求下一页数据
                                    currentPage++;
                                    requestData();
                                    return;
                                }
                            }
                        }
                        mDataList = sortList(mDataList);
                        mAdapter.notifyDataSetChanged();
                        SoundVibratorManager.playSound(1);
                        dismissPgDlg();
                        statisticsPiaoNum();
                    }
                });
    }

    /**
     * 提交请求
     */
    private void requestSubmit() {
        showPgDlg("提交中...");
        LanHuoStatusUpdateRequest request = new LanHuoStatusUpdateRequest();
        List<LanHuoStatusUpdateRequest.Data> dataList = new ArrayList<>();
        for (LanHuoTable item : mDataList) {
            if (item.isScan()) {
                LanHuoStatusUpdateRequest.Data data = new LanHuoStatusUpdateRequest.Data();
                data.setOrderNo(item.getOrderNo());
                data.setStatusType(0);
                data.setStatusValue(2);
                data.setDriverName(sharedPreferUtil.getEmpName());
                data.setDriverPhone(sharedPreferUtil.getValue(Common.USER_PHONE));
                try {
                    data.setLanshouTime(DateHelper.getEithgTzFormat(new Date()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dataList.add(data);
            }
        }
        request.setStatusUpdates(dataList);
        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(NoDataResponse.class)
                .setUrl(Constants.URL_UPDATE_STATUS)
                .setRequestObject(request)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        showToast("揽货成功！");
                        mDataList.clear();
                        requestData();
                    }
                });
    }

    /**
     * 查询用户登录信息
     */
    private void queryLoginInfo() {
        showPgDlg("查询中...");
        Map<String, String> params = new HashMap<>();
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryLoginInfoResponse.class)
                .setUrl(Constants.URL_LOGIN_INFO)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryLoginInfoResponse response = (QueryLoginInfoResponse) obj;
                        if (response.getData() != null) {
                            if (response.getData().getSessionAttrs() != null) {
                                if (response.getData().getSessionAttrs().getLoginUser() != null) {
                                    QueryLoginInfoResponse.DataBean.SessionAttrsBean.LoginUserBean userBean = response.getData().getSessionAttrs().getLoginUser();
                                    sharedPreferUtil.setValue(Common.USER_PHONE, userBean.getPhoneNum());
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 数据排序
     * 一级排序 红>黄>白>绿,getType
     * 二级排序 卡>比>串>标,goodsPriority
     */
    private List<LanHuoTable> sortList(List<LanHuoTable> list) {
        String[] sortNameArr = {"isScan"};
        // true升序,false降序
        boolean[] isAscArr = {true};
        ListUtils.sort(list, sortNameArr, isAscArr);
        return list;
    }

    /**
     * 统计票数
     */
    private void statisticsPiaoNum() {
        tvPiaoNum.setText(String.format("%s", mDataList.size() + " 票"));
        int count = 0;
        for (LanHuoTable item : mDataList) {
            if (item.isScan()) {
                count++;
            }
        }
        tvRealPiaoNum.setText(String.format("%s", count + " 票"));
    }
}
